package com.mo.core.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.mo.core.exception.MoException;
import com.mo.core.exception.MoExceptionEnum;

/**
 * 渲染工具类
 *
 * @author chenxiaodong
 * @date 2018-08-25 14:13
 */
public class RenderUtil {

    /**
     * 渲染json对象
     */
    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        try {
    		response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonObject));
        } catch (IOException e) {
            throw new MoException(MoExceptionEnum.WRITE_ERROR);
        }
    }
    
    /**
     * 请求错误
     */
    public static void renderErrorJson(HttpServletResponse response, Integer code,String message) {
        try {
    		response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String,Object> map = new HashMap<String,Object>();
        	map.put("res", code);
    		map.put("msg", message);
            writer.write(JSON.toJSONString(map));
        } catch (IOException e) {
            throw new MoException(MoExceptionEnum.WRITE_ERROR);
        }
    }
    
    /**
     * 系统异常
     */
    public static void renderExceptionJson(HttpServletResponse response, Integer code,String stackTrace) {
        try {
    		response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String,Object> map = new HashMap<String,Object>();
        	map.put("res", code);
    		map.put("msg", "系统异常");
    		map.put("data",stackTrace );
            writer.write(JSON.toJSONString(map));
        } catch (IOException e) {
            throw new MoException(MoExceptionEnum.WRITE_ERROR);
        }
    }
    
    /**
     * 请求成功,过滤器直接放行即可，暂不使用此方法
     */
    public static void renderSuccessJson(HttpServletResponse response, String message,Object data) {
        try {
    		response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String,Object> map = new HashMap<String,Object>();
	    	map.put("res", 1);
			map.put("msg", message);
			map.put("data",data );
            writer.write(JSON.toJSONString(map));
        } catch (IOException e) {
            throw new MoException(MoExceptionEnum.WRITE_ERROR);
        }
    }
}
